package com.connect.server.handler;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IDisconnectHandler;
import org.xsocket.connection.INonBlockingConnection;

import com.connect.agreement.Packet;
import com.module.chat.ChatManager;
import com.module.chat.ChatPacket;

/**
 * 
 * @author chzcb
 * @email chzcb2008@gmail.com
 * @date 2011-8-31
 *
 */
public class ChatHandler implements IDataHandler, IConnectHandler, IDisconnectHandler {


    private int mark;
    private int size;
    private int channel;
    private byte[] content;
    private int end;
    
    public boolean onData(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, ClosedChannelException, MaxReadSizeExceededException {
        try {
        	while(nbc.available()>0){
        		mark = nbc.readShort();
        		if(mark == 0x4235){
        			size = nbc.readShort();
        			channel = nbc.readByte();
        			content = nbc.readBytesByLength(size);
        			end = nbc.readShort();
        			if(end == 0x5324){
        				ChatPacket packet = new ChatPacket(channel,content);
        				ChatManager.update(nbc, packet);
        			}
        			else
        			{
        				System.out.println("包结尾错误");
        			}
        		}
        		else
        		{
        			System.out.println("包头标识错误");
        		}
        	}
        } catch (Exception ex) {
            System.out.println("ReceiveDataException: " + ex.getMessage());
        }
        return true;
    }
    public boolean onConnect(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, MaxReadSizeExceededException {
        try {
        	ChatManager.addConnect(nbc);
        } catch (Exception ex) {
            System.out.println("onConnect: " + ex.getMessage());
        }
        return true;
    }

    public boolean onDisconnect(INonBlockingConnection nbc) throws IOException {
        try {
        	ChatManager.removeConnect(nbc);
        } catch (Exception ex) {
            System.out.println("onDisconnect: " + ex.getMessage());
        }
        return true;
    }
}